package com.adtech.farmProducts.base;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcV;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.widgets.dialog.CustomDialog;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.activities.activity.LoginActivity;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.model.NFCResult;
import com.adtech.farmProducts.utils.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hachi.publishplugin.activity.CertPlugin;
import com.hachi.publishplugin.activity.ValiPlugin;
import com.hachi.publishplugin.bean.Result;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * NFC 父类
 */

public abstract class BaseNfcActivity extends BaseActivity {

    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;

    private IntentFilter[] filters;
    private String[][] tehcLists;


    /**
     * 启动Activity，界面可见时
     */
    @Override
    protected void onStart() {
        super.onStart();
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        //一旦截获NFC消息，就会通过PendingIntent调用窗口
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
        IntentFilter ndefFilter = new IntentFilter("android.nfc.action.NDEF_DISCOVERED");
        IntentFilter techFilter = new IntentFilter("android.nfc.action.TECH_DISCOVERED");
        IntentFilter tagFilter = new IntentFilter("android.nfc.action.TAG_DISCOVERED");
        try {
            ndefFilter.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            e.printStackTrace();
        }
        ndefFilter.addDataScheme("d156000139");
        filters = new IntentFilter[]{ndefFilter, techFilter, tagFilter};
        tehcLists = new String[][]{{NfcA.class.getName(), NfcV.class.getName(), MifareClassic.class.getName(), MifareUltralight.class.getName(), NdefFormatable.class.getName()}};
    }

    public void isNFC() {
        PackageManager packageManager = this.getPackageManager();
        boolean b1 = packageManager
                .hasSystemFeature(PackageManager.FEATURE_NFC);
        if (!b1) {
            App.getInstance().showMessage("该手机不支持NFC");
            return;
        }
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
            App.getInstance().showMessage("请在系统设置中先启用NFC功能！");
            startActivity(new Intent("android.settings.NFC_SETTINGS"));
        }
    }

    /**
     * 获得焦点，按钮可以点击
     */
    @Override
    public void onResume() {
        super.onResume();
        //设置处理优于所有其他NFC的处理
        if (mNfcAdapter != null)
            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, filters, tehcLists);
    }

    /**
     * 暂停Activity，界面获取焦点，按钮可以点击
     */
    @Override
    public void onPause() {
        super.onPause();
        //恢复默认状态
        if (mNfcAdapter != null)
            mNfcAdapter.disableForegroundDispatch(this);
    }

    public CustomDialog dialog;

    public void onDialogNFC() {
        final CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
        View layout = LayoutInflater.from(mContext).inflate(R.layout.dialog_nfc, null);
        builder.setContentView(layout);
        layout.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        builder.setCanceledOnTouchOutside(false);
        builder.setGravity(Gravity.CENTER);
        builder.setDialogWidthAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        builder.setDialogHeightAndPX(WindowManager.LayoutParams.WRAP_CONTENT);
        dialog = builder.create();
        dialog.show();
        isNFC();
    }


    /**
     * 读取信息
     */
    public NFCResult resolveVerifyIntent(Tag detectedTag) {
        System.out.println("----------onNewIntent");
        //获取Tag对象
        if (detectedTag == null) {
            Toast.makeText(this, "NFC标签未探测成功，请将标签靠近手机NFC检测区域再次探测", Toast.LENGTH_SHORT).show();
            return null;
        }
        //写非NDEF格式的数据
        String[] techList = detectedTag.getTechList();
        boolean haveMifareUltralight = false;
        boolean haveNfcA = false;
        for (String tech : techList) {
            //如果有Mifare则为老版本芯片，没有但有NFCA则为新版芯片
            if (tech.indexOf("MifareUltralight") >= 0) {
                haveMifareUltralight = true;
                break;
            }
        }
        if (!haveMifareUltralight) {
            for (String tech : techList) {
                if (tech.indexOf("NfcA") >= 0) {
                    haveNfcA = true;
                    break;
                }
            }
        }
        //如果两种都没有，则弹出提示不支持
        if (!haveNfcA && !haveMifareUltralight) {
            App.getInstance().showMessage("不支持NfcA数据格式", Toast.LENGTH_SHORT);
            return null;
        }
        //调用组件(验证功能)
        System.out.println("AccountManagers.getThirdToken()" + AccountManagers.getThirdToken());
        try{
            return result(ValiPlugin.vali14443(this, detectedTag, "2f26baeaebb64d4608bd91ab61401c24",AccountManagers.getThirdToken(),"",""));
        }catch (Exception e){
            App.getInstance().showMessage("芯片未知错误！");
        }
        return null;
    }

    /**
     * 写入证书
     *
     * @param detectedTag
     * @return
     */
    public NFCResult resolveReadIntent(Tag detectedTag) {
        System.out.println("----------resolveReadIntent");
        //获取Tag对象
        if (detectedTag == null) {
            App.getInstance().showMessage("NFC标签未探测成功，请将标签靠近手机NFC检测区域再次探测");
            return null;
        }
        //写非NDEF格式的数据
        String[] techList = detectedTag.getTechList();
        boolean haveMifareUltralight = false;
        boolean haveNfcA = false;
        for (String tech : techList) {
            //如果有Mifare则为老版本芯片，没有但有NFCA则为新版芯片
            if (tech.indexOf("MifareUltralight") >= 0) {
                haveMifareUltralight = true;
                break;
            }
        }
        if (!haveMifareUltralight) {
            for (String tech : techList) {
                if (tech.indexOf("NfcA") >= 0) {
                    haveNfcA = true;
                    break;
                }
            }
        }
        //如果两种都没有，则弹出提示不支持
        if (!haveNfcA && !haveMifareUltralight) {
            App.getInstance().showMessage("不支持NfcA数据格式", Toast.LENGTH_SHORT);
            return null;
        }
        //调用组件(写入功能)
        System.out.println("AccountManagers.getThirdToken()" + AccountManagers.getThirdToken());
        try{
            return result(CertPlugin.cert14443(this, detectedTag, "2f26baeaebb64d4608bd91ab61401c24",AccountManagers.getThirdToken(),"",""));
        }catch (Exception e){
            App.getInstance().showMessage("芯片未知错误！");
        }
        return null;
    }

    private NFCResult result(Result result) {
        NFCResult nfcResult = new NFCResult();
        nfcResult.setResult(result);
        nfcResult.setState(false);
        switch (result.getCode()) {
            case 401:
                nfcResult.setMessage("请更换标签");
                break;
            case 402:
                nfcResult.setMessage("读取证书失败，请重新尝试");
                break;
            case 403:
                nfcResult.setMessage("写入证书失败，请重新尝试");
                break;
            case 404:
                nfcResult.setMessage("时间写入失败,请重新尝试");
                break;
            case 405:
                nfcResult.setMessage("写入NDEF失败,请重新尝试");
                break;
            case 406:
                nfcResult.setMessage("读取数据失败,请重新尝试");
                break;
            case 407:
                nfcResult.setMessage("读取失败,请重新尝试");
                break;
            case 408:
                nfcResult.setMessage("写入标签失败,请重新尝试");
                break;
            case 409:
                nfcResult.setMessage("状态位读取失败,请重新尝试");
                break;
            case 410:
                nfcResult.setMessage("读取标志位失败,请重新尝试");
                break;
            case 420:
                nfcResult.setMessage("未授权");
                break;
            case 421:
                nfcResult.setMessage("私钥过期,正在重新获取");
                getToken();
                LoginActivity.show(mContext);
                break;
            case 500:
                nfcResult.setMessage("网络请求失败,请重新尝试");
                break;
            case 501:
                nfcResult.setMessage("请查证后重新尝试");
                break;
            case 502:
                nfcResult.setMessage("验证失败");
                break;
            case 200:
                nfcResult.setMessage("验证成功，标签未开启");
                nfcResult.setState(true);
                break;
            case 201:
                nfcResult.setMessage("验证成功，标签已开启");
                nfcResult.setState(true);
                break;
            case 202:
                nfcResult.setMessage("发证成功");
                nfcResult.setState(true);
                break;
            default:
                nfcResult.setMessage("未知错误");
                break;
        }
        System.out.println("---result:" + new Gson().toJson(nfcResult));
        nfcResult.setMessage(nfcResult.getMessage()+result.getCode());
        return nfcResult;
    }

    /**
     * 刷新查询第三方token
     */
    private void getToken() {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("userType", Constants.userType);//1、操作用户刷新token，2、游客刷新token
        okHttpClient.posts(Common.Constant.API_IP + "guest/refreshToken", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModel = getAnalysis(response, type, "刷新查询第三方token");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null && !"".equals(rspModel.getData())) {//保存新Token
                            FUserInfo userInfo = new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class);
                            userInfo.setThirdToken(rspModel.getData());
                            AccountManagers.login(userInfo.getUserId(), userInfo.getToken(), new Gson().toJson(userInfo), userInfo.getThirdToken());
                            userInfo = new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class);
                            System.out.println("userInfo" + new Gson().toJson(userInfo));
                            App.getInstance().showMessage("请再次贴近NFC");
                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }
}
